package zserver

import (
	"errors"
	"fmt"
	"net"
	"zinx/zinterface"
)

type Zserver struct {
	Name      string // 服务器名称
	IP        string // 监听地址
	Port      int    // 监听端口
	IPVersion string // 监听方法
}

// 实现连接绑定的方法
// TODO: 将方法交由用户开发端实现
// 简单回显
func CallBackToClient(conn *net.TCPConn, data []byte, cnt int) error {
	fmt.Println("Write Back To Client...")
	if _, err := conn.Write(data[:cnt]); err != nil {
		fmt.Println("!!!ERROR When Writing Back To Client: ", err)
		return errors.New("Call Back Api ERROR")
	}

	return nil
}

func (z *Zserver) Start() {
	fmt.Printf("START SERVER '%s' on IP '%s:%d'", z.Name, z.IP, z.Port)

	go func() {
		// 获取socket
		tcpAddr, err := net.ResolveTCPAddr(z.IPVersion, fmt.Sprintf("%s:%d", z.IP, z.Port))
		if err != nil {
			fmt.Println("ERROR ON START SERVER :", err)
			return
		}

		// 开始监听
		listenner, err := net.ListenTCP(z.IPVersion, tcpAddr)
		if err != nil {
			fmt.Println("ERROR ON LISTENNING ADDR: ", err)
			return
		}

		// 简单写个cid
		var cid uint32
		cid = 0

		// 阻塞地等待客户端连接，处理客户端业务
		for {
			conn, err := listenner.AcceptTCP()
			if err != nil {
				fmt.Println("ERROR ON ACCEPT CLIENT: ", err)
				continue
			}

			dealConn := NewConnector(conn, cid, CallBackToClient)
			cid++

			go dealConn.Start()
		}
	}()

}

func (z *Zserver) Stop() {

}

func (z *Zserver) Serve() {
	z.Start()

	select {}
}

func New(name string) zinterface.Zinterface {
	zs := &Zserver{
		Name:      name,
		IP:        "0.0.0.0",
		Port:      8999,
		IPVersion: "tcp4",
	}

	return zs
}
